﻿using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.SignalR;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using SignalR_HubTest;
using System;
using System.Text.Json;

var builder = WebApplication.CreateBuilder(args);
// 配置监听端口为 5000
builder.WebHost.UseUrls("http://localhost:5000"); // 关键配置
builder.Services.AddSignalR(); // 注册 SignalR 服务

var app = builder.Build();
app.MapHub<UploadHub>("/UploadHub"); // 路由为 /UploadHub

// 启动服务
_ = app.RunAsync();

Console.WriteLine("SignalR Hub 启动成功：http://localhost:5000/UploadHub");

var hubContext = app.Services.GetRequiredService<IHubContext<UploadHub>>();

// 控制台循环输入并推送消息
while (true)
{
    Console.Write("\n请输入状态内容（如 Online、Error）：");
    string status = Console.ReadLine();
    if (string.IsNullOrWhiteSpace(status)) continue;

    var msg = new ServerSystemStatus
    {
        Status = status,
        Version = status+"1.6.6", // 假设版本号为 1.0.0
        Timestamp = DateTime.Now
    };

    string json = JsonSerializer.Serialize(msg, new JsonSerializerOptions
    {
        WriteIndented = true,
        Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping
    });

    Console.WriteLine("推送 JSON：" + json);

    foreach (var kvp in UploadHub.Subscriptions)
    {
        var connId = kvp.Key;
        var types = kvp.Value;

        if (types.Contains("Status"))
        {
            await hubContext.Clients.Client(connId).SendAsync("SystemStatus", json);
        }
    }
}
